package com.neusoft.neumooc.controller;

import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.ArrayList;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.neusoft.core.common.BaseController;
import com.neusoft.core.common.conf.Params;
import com.neusoft.core.util.FileUtils;
import com.neusoft.core.util.IDUtil;
import com.neusoft.neumooc.service.BackContentService;
import com.neusoft.neumooc.service.ColumnService;
import com.neusoft.neumooc.vo.BackContentVO;
import com.neusoft.neumooc.vo.ColumnVO;

@Controller
@RequestMapping(value = "/content")
public class BackContentController extends BaseController {
    
    @Autowired
    private BackContentService backContentService;
    
    @Autowired
    private ColumnService columnService;
    
    private static final String UPLOAD_IMG_PATH = "/resources/upload/uploadimg/";
    private static final String UPLOAD_FILE_PATH = "/resources/upload/uploadfile/";
    
    /**
     * 保存内容（新增或更新）
     */
    @ResponseBody
    @RequestMapping(value = "/save")
    public Map<String, Object> save(BackContentVO content, 
            @RequestParam(value = "picFile", required = false) MultipartFile picFile,
            @RequestParam(value = "attachFile", required = false) MultipartFile attachFile,
            HttpServletRequest request) {
        Map<String, Object> retMap = new HashMap<String, Object>();
        try {
            String realPath = request.getSession().getServletContext().getRealPath("/");
            log.info("realPath: " + realPath);
            log.info("picFile: " + picFile);
            
            // 处理图片上传
            if(picFile != null && !picFile.isEmpty()) {
                // 检查图片类型
                String contentType = picFile.getContentType();
                if(!contentType.startsWith("image/")) {
                    retMap.put(Params.RET_CODE, Params.RET_CODE_ERROR);
                    retMap.put(Params.RET_OBJ, "不支持的图片类型");
                    return retMap;
                }
                
                String originalFilename = picFile.getOriginalFilename();
                String newFilename = UUID.randomUUID().toString() + originalFilename.substring(originalFilename.lastIndexOf("."));
                
                // 确保路径分隔符正确
                String uploadPath = realPath.endsWith("/") || realPath.endsWith("\\") ? 
                    realPath + UPLOAD_IMG_PATH.substring(1) : 
                    realPath + UPLOAD_IMG_PATH;
                    
                File targetFile = new File(uploadPath + newFilename);
                if(!targetFile.getParentFile().exists()) {
                    targetFile.getParentFile().mkdirs();
                }
                picFile.transferTo(targetFile);
                // 只保存文件名
                content.setPic(newFilename);
                log.info("图片保存路径: " + targetFile.getAbsolutePath());
            }
            
            // 处理附件上传
            if(attachFile != null && !attachFile.isEmpty()) {
                // 检查文件类型
                String contentType = attachFile.getContentType();
                if(contentType.contains("exe") || contentType.contains("bat")) {
                    retMap.put(Params.RET_CODE, Params.RET_CODE_ERROR);
                    retMap.put(Params.RET_OBJ, "不支持的文件类型");
                    return retMap;
                }
                
                String originalFilename = attachFile.getOriginalFilename();
                String newFilename = UUID.randomUUID().toString() + originalFilename.substring(originalFilename.lastIndexOf("."));
                
                // 确保路径分隔符正确
                String uploadPath = realPath.endsWith("/") || realPath.endsWith("\\") ? 
                    realPath + UPLOAD_FILE_PATH.substring(1) : 
                    realPath + UPLOAD_FILE_PATH;
                    
                File targetFile = new File(uploadPath + newFilename);
                if(!targetFile.getParentFile().exists()) {
                    targetFile.getParentFile().mkdirs();
                }
                attachFile.transferTo(targetFile);
                // 只保存文件名
                content.setFile(newFilename);
                log.info("附件保存路径: " + targetFile.getAbsolutePath());
            }
            
            boolean result;
            if(content.getContentId() == null || content.getContentId().trim().isEmpty()) {
                // 新增
                content.setContentId(IDUtil.getID());
                content.setViewTimes("0");
                content.setStatus("1");
                content.setCreateTime(new Date());
                content.setCreateUser((String)request.getSession().getAttribute("userId"));
                result = backContentService.addContent(content);
            } else {
                // 更新
                content.setEditTime(new Date());
                content.setEditUser((String)request.getSession().getAttribute("userId"));
                result = backContentService.updateContent(content);
            }
            
            if(result) {
                retMap.put(Params.RET_CODE, Params.RET_CODE_SUCCESS);
                retMap.put(Params.RET_OBJ, "保存成功");
            } else {
                retMap.put(Params.RET_CODE, Params.RET_CODE_ERROR);
                retMap.put(Params.RET_OBJ, "保存失败");
            }
        } catch (Exception e) {
            log.error("保存内容失败", e);
            retMap.put(Params.RET_CODE, Params.RET_CODE_ERROR);
            retMap.put(Params.RET_OBJ, "保存内容失败");
        }
        return retMap;
    }
    
    /**
     * 内容列表页面
     */
    @RequestMapping("/list")
    public String list(String columnId, Model model) {
        try {
            List<BackContentVO> contents = backContentService.getContentsByColumnId(columnId);
            model.addAttribute("contents", contents);
            model.addAttribute("columnId", columnId);
            return "content/list";
        } catch (Exception e) {
            log.error("获取内容列表失败", e);
            return "error";
        }
    }
    
    /**
     * 添加内容页面
     */
    @RequestMapping("/add")
    public String add(String columnId, Model model) {
        model.addAttribute("columnId", columnId);
        return "content/add";
    }
    
    /**
     * 编辑内容页面
     */
    @RequestMapping("/edit")
    public String edit(String contentId, Model model) {
        try {
            BackContentVO content = backContentService.getContentById(contentId);
            model.addAttribute("content", content);
            return "content/edit";
        } catch (Exception e) {
            log.error("获取内容失败", e);
            return "error";
        }
    }
    
    /**
     * 删除内容
     */
    @RequestMapping("/delete")
    @ResponseBody
    public Map<String, Object> delete(String contentId) {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            if (backContentService.deleteContent(contentId)) {
                result.put("RET_CODE", "SUCCESS");
                result.put("RET_MSG", "删除成功");
            } else {
                result.put("RET_CODE", "FAILED");
                result.put("RET_MSG", "删除失败");
            }
        } catch (Exception e) {
            log.error("删除内容失败", e);
            result.put("RET_CODE", "FAILED");
            result.put("RET_MSG", "删除失败");
        }
        return result;
    }
    
    /**
     * 更新内容状态
     */
    @RequestMapping("/updateStatus")
    @ResponseBody
    public Map<String, Object> updateStatus(String contentId, String status) {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            if (backContentService.updateContentStatus(contentId, status)) {
                result.put("RET_CODE", "SUCCESS");
                result.put("RET_MSG", "更新状态成功");
            } else {
                result.put("RET_CODE", "FAILED");
                result.put("RET_MSG", "更新状态失败");
            }
        } catch (Exception e) {
            log.error("更新内容状态失败", e);
            result.put("RET_CODE", "FAILED");
            result.put("RET_MSG", "更新状态失败");
        }
        return result;
    }
    
    /**
     * 搜索内容
     */
    @ResponseBody
    @RequestMapping("/doSearch")
    public Map<String, Object> search(String columnId, String contentMark, 
            String createUser, String editUser, String status) {
        Map<String, Object> retMap = new HashMap<String, Object>();
        try {
            BackContentVO searchParams = new BackContentVO();
            searchParams.setColumnId(columnId);
            searchParams.setContentMark(contentMark);
            searchParams.setCreateUser(createUser);
            searchParams.setEditUser(editUser);
            searchParams.setStatus(status);
            
            List<BackContentVO> contents = backContentService.searchContents(searchParams);
            retMap.put(Params.RET_CODE, Params.RET_CODE_SUCCESS);
            retMap.put(Params.RET_OBJ, contents);
        } catch (Exception e) {
            log.error("搜索内容失败", e);
            retMap.put(Params.RET_CODE, Params.RET_CODE_ERROR);
            retMap.put(Params.RET_OBJ, "搜索内容失败");
        }
        return retMap;
    }
    
    /**
     * 跳转到搜索页面
     */
    @RequestMapping("/search")
    public String searchPage(Model model) {
        try {
            // 获取所有参与搜索的栏目
            List<ColumnVO> columns = columnService.getAllColumns();
            List<ColumnVO> searchableColumns = new ArrayList<>();
            for(ColumnVO column : columns) {
                if("1".equals(column.getCanSearch())) {
                    searchableColumns.add(column);
                }
            }
            model.addAttribute("columns", searchableColumns);
            return "content/search";
        } catch (Exception e) {
            log.error("获取栏目列表失败", e);
            return "error";
        }
    }
} 